package com.codemeta.bokit.mybatis.core.validation;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.extension.service.IService;
import com.codemeta.bokit.mybatis.core.validation.annotation.PrimaryKey;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.util.CollectionUtils;

/**
 * 主键是否存在 注解校验
 *
 * @author hice
 */
public class PrimaryKeyValidator implements ConstraintValidator<PrimaryKey, Serializable> {

    private final List<IService> mappers = new ArrayList<>();

    @Override
    public void initialize(PrimaryKey annotation) {
        if (annotation.value().length > 0) {
            for (Class<? extends IService> clazz : annotation.value()) {
                // hutool.SpringUtil需要预先注入
                mappers.add(SpringUtil.getBean(clazz));
            }
        }
    }

    @Override
    public boolean isValid(Serializable value, ConstraintValidatorContext context) {
        if (validPkey(value) || CollectionUtils.isEmpty(mappers)) {
            // 如果参数为空或者小于0，默认不校验，即校验通过
            return true;
        }
        return mappers.stream().anyMatch(mapper -> Objects.nonNull(mapper.getById(value)));
    }

    /**
     * 参数是否需要校验
     *
     * @param value .
     * @return .
     */
    private boolean validPkey(Serializable value) {
        if (value == null) {
            return true;
        } else if (value instanceof String) {
            return StrUtil.isBlankOrUndefined((String) value);
        } else if (value instanceof Number) {
            return NumberUtil.parseLong(value.toString()) <= 0;
        }
        return true;
    }
}